package com.tqjc.work.step;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tqjc.entity.SteelPlate;
import com.tqjc.entity.Task;
import com.tqjc.entity.TaskApart;
import com.tqjc.exception.TaskRunningException;
import com.tqjc.service.SteelPlateService;
import com.tqjc.service.impl.TaskApartServiceImpl;
import com.tqjc.service.impl.TaskServiceImpl;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.utils.PlcOperator;
import com.tqjc.work.TaskCallback;
import com.tqjc.work.TaskStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Slf4j
@Component
@Scope("prototype")
public class OfflinePlaceStep extends TaskApart implements TaskCallback {
    @Resource
    PlcOperator plcOperator;

    @Resource
    SteelPlateService steelPlateService;

    @Resource
    TaskStatus taskStatus;

    public OfflinePlaceStep() {
        this.setType("offlinePlace");
    }

    @Override
    public void onPreExecute() {
        try {
            log.info("开始执行步骤前置，{}", getType());
            setBeginTime(new Date());

            //设置工作状态
            /*WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep(getType());
            status.setNowSteelNum(getTask().getSteelNum());
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);*/
            log.info("步骤前置执行结束，{}", getType());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(getType()+"前置出现异常", e);
        }
    }

    @Override
    public void onPostExecute() {
        try {
            log.info("开始执行步骤后置，{}", getType());
            setEndTime(new Date());

            getTask().setTaskStatus(2);
            SpringUtils.getBean(TaskServiceImpl.class).saveOrUpdate(getTask());
            SpringUtils.getBean(TaskApartServiceImpl.class).insert(this);
            //修改步骤状态
            /*WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep("");
            status.setNowSteelNum("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);
            //增加钢板库存
            Stock stock = stockService.queryById(getTask().getStockId());*/
            List<SteelPlate> steels2Place=null;
            if(steels2Place.size()>0){
                for(SteelPlate item:steels2Place){
                    //获取当前垛位所有的钢板，判断层数
                    QueryWrapper<SteelPlate> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("area", "stock_" + getTask().getStockId());
                    List<SteelPlate> steelPlates = steelPlateService.list(queryWrapper);
                    Integer tier = steelPlates.size() + 1;

                    item.setStockId(getTask().getStockId());
                    item.setTier(tier);
                    steelPlateService.insert(item);
                }
            }
            log.info("步骤后置执行结束，{}", getType());
            //清除bean
            destroy();
        } catch (Exception e) {
            log.error(getType()+"后置出现异常", e);
            e.printStackTrace();
        }
    }


    @Override
    public void setTaskApartByTask(Task task) {
        this.setCallback(this);
        super.setTaskApartByTask(task);

    }


    @Override
    public void customAction() throws TaskRunningException {
        try {
            //从天车PLC获取钢板号作为放置人物的钢板号
//            String steelNum = plcOperator.readValueByLabelAndCraneType(WorkConst.STEEL_NUM, getCraneType());
            //String steelNum = getTask().getSteelNum();
            //this.setSteelId(steelNum);
            String steelNum ="";
            List<SteelPlate> steels2Place=null;
            for(int i=0;i<steels2Place.size();i++){
                if(i==0){
                    steelNum=steels2Place.get(i).getSteelId();
                }else{
                    steelNum+=","+steels2Place.get(i).getSteelId();
                }
            }
            this.setSteelId(steelNum);
            this.setSteelType(steels2Place.get(0).getSteelType());
            //写入任务坐标
            log.info("步骤{}写入PLC开始", getType());
            /*plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_X, getEndX().toString(), craneType);
            plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_Y, getEndY().toString(), craneType);
            List<SteelPlate> steels=getTask().getSteels4Offline();
            Integer height=0;//如果是suck多块了放，z轴要加上已吸钢板厚度
            for(int i=0;i<steels.size();i++){
                height+= steels.get(i).getThickness();
            }
            plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_Z, (getEndZ()+height)+"", craneType);  //放钢板，z轴值要加上已吸几块钢板的厚度

            //写入任务类型
//            TODO:等待确认任务类型
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_TYPE, "1", craneType);

            //写入任务开始
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_START, "1", craneType);*/
            log.info("步骤{}写入PLC完成,等待任务完成", getType());
            boolean isFinished = false;
            while (!isFinished) {
                /*if (Boolean.parseBoolean(plcOperator.readValueByLabelAndCraneType(WorkConst.STEP_FINISH, craneType))) {
                    isFinished = true;
                    log.info("PLC反馈步骤{}完成", getType());
                }*/

                //TODO:测试使用
                Thread.sleep(5000);
                isFinished = true;
                Thread.sleep(500);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new TaskRunningException(e.getMessage(),null);
        }
    }


    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
